#ifndef _WIN32

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>

#include <iostream>
#include "headers/serial.hpp"

#include "headers/all_control_define.hpp"

using namespace std;

struct termios Opt_COM;
int fd = -1;

//�򿪲����ô��ڣ�����żУ�飩 
bool init_serial(){
	
	fd = open("/dev/ttyTHS2", O_RDWR|O_NOCTTY); //Serial port 1 on TX
	//fd = open("/dev/ttyS0", O_WRONLY|O_NOCTTY|O_DSYNC); //Serial port 0 on TX

	if (tcgetattr(fd, &Opt_COM) == -1) {
		perror("SetupSerial 1");
		return false;
	};

	cfmakeraw(&Opt_COM);

	tcflush(fd, TCIOFLUSH);

	cout << "fd: " << fd << endl;

	fcntl(fd, F_SETFL, 0);

	cfsetospeed(&Opt_COM, B115200);
	cfsetispeed(&Opt_COM, B115200);
	
	Opt_COM.c_cflag &= ~CSIZE;
	Opt_COM.c_cflag |= CS8;
	
	#ifdef _EVEN
	Opt_COM.c_cflag |= PARENB;
	Opt_COM.c_cflag &= ~PARODD;
	Opt_COM.c_iflag |= INPCK;
	#endif
	
	#ifdef _ODD
	Opt_COM.c_cflag |= PARENB;
	Opt_COM.c_cflag |= PARODD;
	Opt_COM.c_iflag |= INPCK;
	#endif
	
	#ifdef _NONE
	Opt_COM.c_cflag &= ~PARENB;
	Opt_COM.c_iflag &= ~(INPCK | ICRNL | IXON | IXOFF);
	#endif
	
	Opt_COM.c_cflag &= ~CSTOPB;
	Opt_COM.c_cflag &= ~CRTSCTS;

	tcflush(fd, TCIOFLUSH);
	
	tcsetattr(fd, TCSANOW, &Opt_COM);
	
	return true;
	
}

int close_serial(){
	return close(fd);
}

int send_message(void *msg_ptr, size_t len){
	return write(fd, msg_ptr, len);
}

void clean_serial(){
	tcflush(fd, TCIOFLUSH);
	return;
}

#endif